exports.searchTeamCommissionRecord = function (req, res) {

  //获取参数信息
  var bodyParams = req.routeInfo.bodyParams;

  //最终结果
  var resultData = {};

  //销售人员列表
  var salesData = [];

  //代理商列表
  var agentData = [];

  //利润分成数据
  var profitSharingRecordData = [];

  //1.查询该战略伙伴是否有自定义提成规则设置
  function searchCustomCommissionRules(cb) {

    R.SEND_HTTP(
      req,
      res,
      {
        url: CORE_APIConfig.coreAPI.organizationStructureExtensionInfoSearch.Request_Api_Url + "/os_id/" + bodyParams.os_id,
        method: 'POST',
        data: {
          fields: "osei_strategic_cooperation_percentage,osei_agent_percentage"
        }
      },
      function (data) {

        resultData.commissionRulesData = data.result.data[0].osei_strategic_cooperation_percentage;
        resultData.agentCommissionRulesData = data.result.data[0].osei_agent_percentage;

        cb();

      }
    )
  }

  //2.判断是否需要进行统一规则的获取
  function searchGlobalRules(cb) {

    //如果不为0，直接使用自己的规则，否则需要获取统一规则
    if (resultData.commissionRulesData != '0') {
      return cb();
    }


    R.SEND_HTTP(
      req,
      res,
      {
        url: CORE_APIConfig.coreAPI.artCommissionConfigSearch.Request_Api_Url,
        method: 'GET'
      },
      function (data) {

        resultData.commissionRulesData = data.result.data[0].cc_strategic_cooperation_percentage;
        resultData.agentCommissionRulesData = data.result.data[0].cc_agent_percentage;

        cb();

      }
    )

  }

  //查询该战略下的销售人员
  function searchAgentSales(cb) {

    R.SEND_HTTP(
      req,
      res,
      {
        url: CORE_APIConfig.coreAPI.userSearch.Request_Api_Url + "/u_master_osid/" + bodyParams.os_id,
        method: 'POST',
        data: {
          fields: `
                      u_id,
                      u_nickname
                  `
        }
      },
      function (data) {

        var userArr = data.result.data;

        salesData = userArr;

        cb();

      }
    )

  }

  //查询每个销售的订单相关信息
  function searchSalesOrder(cb) {

    F.SerialEach(salesData, function (item, index, callback) {

      //获取该代理下所有销售的订单数据
      R.SEND_HTTP(
        req,
        res,
        {
          url: config.external_server.apiAddress + "/organization/search_art_product_order/apo_status/1/apo_invite_code/" + item.u_id,
          method: 'POST',
          data: {
            fields: `apo_real_pay`
          }
        },
        function (data) {

          //计算成交总数 和 成交金额
          var buyCount = data.result.data.length;
          var buyMoney = 0.0;

          for (var i = 0; i < data.result.data.length; i++) {
            buyMoney += parseFloat(data.result.data[i].apo_real_pay);
          }

          item.buyCount = buyCount;
          item.buyMoney = buyMoney.toFixed(2);

          callback();

        }
      )

    }, cb)

  }

  //计算所有销售的总成交数 和 成交金额
  function searchAllSalesOrder(cb) {

    var allBuyCount = 0;
    var allBuyMoney = 0.0;
    var allCommissionMoney = 0.0;

    for (var i = 0; i < salesData.length; i++) {

      allBuyCount += parseInt(salesData[i].buyCount);
      allBuyMoney += parseFloat(salesData[i].buyMoney);

    }

    //计算提成金额
    allCommissionMoney = allBuyMoney * (resultData.commissionRulesData / 100);

    resultData.allBuyCount = allBuyCount;
    resultData.allBuyMoney = allBuyMoney;
    resultData.allCommissionMoney = allCommissionMoney.toFixed(2);

    cb();

  }

  //查询该代理商的结算记录
  function searchSettlementData(cb) {

    R.SEND_HTTP(
      req,
      res,
      {
        url: CORE_APIConfig.coreAPI.settlementRecordSearch.Request_Api_Url + "/sr_osid/" + bodyParams.os_id + "/sort_order/sr_create_time-desc",
        method: 'POST'
      },
      function (data) {

        resultData.settlementData = data.result.data;

        cb();

      }
    )
  }

  //查询利润分成记录信息
  function searchProfitSharing(cb) {

    R.SEND_HTTP(
      req,
      res,
      {
        url: CORE_APIConfig.coreAPI.profitSharingRecordSearch.Request_Api_Url + "/psr_osid/" + bodyParams.os_id,
        method: 'POST',
        data: {
          fields: "psr_id,psr_sales_profit_sharing_money,psr_reward_money"
        }
      },
      function (data) {

        profitSharingRecordData = data.result.data;

        cb();

      }
    )

  }

  //计算剩余结算金额
  function calculateResidualSettlement(cb) {

    //获取所有利润分成金额
    var totalProfits = 0.0;
    for (var i = 0; i < profitSharingRecordData.length; i++) {
      totalProfits += (parseFloat(profitSharingRecordData[i].psr_sales_profit_sharing_money) + parseFloat(profitSharingRecordData[i].psr_reward_money));
    }

    //获取已结算金额
    var totalSettlement = 0.0;
    for (var i = 0; i < resultData.settlementData.length; i++) {
      totalSettlement += parseFloat(resultData.settlementData[i].sr_money);
    }

    //计算剩余结算金额
    var remainingMoney = totalProfits - totalSettlement;

    resultData.totalProfits = totalProfits;
    resultData.totalSettlement = totalSettlement;
    resultData.remainingMoney = remainingMoney;

    cb();

  }

  //查询该战略下的代理商
  function searchAgent(cb) {

    R.SEND_HTTP(
      req,
      res,
      {
        url: CORE_APIConfig.coreAPI.organizationStructureExtensionInfoSearch.Request_Api_Url + "/no/os_master_type-0/os_fid/" + bodyParams.os_id + "/os_is_delete/0",
        method: 'POST',
        data: {
          fields: `
                      os_id,
                      os_name,
                      osei_phone
                  `
        }
      },
      function (data) {

        agentData = data.result.data;

        cb();

      }
    )
  }

  //查询代理的成交数以及销售总额
  function searchAgentOrder(cb) {


    F.SerialEach(agentData, function (item, index, callback) {

      R.SEND_HTTP(
        req,
        res,
        {
          url: CORE_APIConfig.coreAPI.userSearch.Request_Api_Url + "/u_master_osid/" + item.os_id,
          method: 'POST',
          data: {
            fields: `
                              u_id,
                              u_nickname
                          `
          }
        },
        function (data) {

          var userArr = data.result.data;

          //拼接为in语句所需数据
          var userInStr = "";
          for (var i = 0; i < userArr.length; i++) {
            userInStr += userArr[i].u_id + ","
          }
          userInStr = userInStr.substring(0, userInStr.length - 1);

          //获取该代理下所有销售的订单数据
          R.SEND_HTTP(
            req,
            res,
            {
              url: config.external_server.apiAddress + "/organization/search_art_product_order/apo_status/1/in/apo_invite_code-" + userInStr,
              method: 'POST',
              data: {
                fields: `apo_real_pay`
              }
            },
            function (data) {

              //计算成交总数 和 成交金额
              var buyCount = data.result.data.length;
              var buyMoney = 0.0;

              for (var i = 0; i < data.result.data.length; i++) {
                buyMoney += parseFloat(data.result.data[i].apo_real_pay);
              }

              item.buyCount = buyCount;
              item.buyMoney = buyMoney.toFixed(2);

              callback();

            }
          )

        }
      )
    }, cb);

  }

  //计算所有代理的总成交数，成交金额，提成金额等
  function searchAllAgentOrder(cb) {

    var agentAllBuyCount = 0;
    var agentAllBuyMoney = 0.0;
    var agentAllCommissionMoney = 0.0;

    for (var i = 0; i < agentData.length; i++) {

      agentAllBuyCount += parseInt(agentData[i].buyCount);
      agentAllBuyMoney += parseFloat(agentData[i].buyMoney);

    }


    //计算提成金额
    agentAllCommissionMoney = agentAllBuyMoney * (resultData.agentCommissionRulesData / 100);

    resultData.agentAllBuyCount = agentAllBuyCount;
    resultData.agentAllBuyMoney = agentAllBuyMoney;
    resultData.agentAllCommissionMoney = agentAllCommissionMoney.toFixed(2);

    cb();

  }


  F.Serial([
    searchCustomCommissionRules,
    searchGlobalRules,
    searchAgentSales,
    searchSalesOrder,
    searchAllSalesOrder,
    searchSettlementData,
    searchProfitSharing,
    calculateResidualSettlement,
    searchAgent,
    searchAgentOrder,
    searchAllAgentOrder
  ], () => {
    RES.successResponse(res, resultData);
  })

}